package com.effectivcrm.startup;

import groovy.util.logging.Slf4j;

import java.util.List;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.Resource;

import com.effectivcrm.domain.ui.Form;
import com.effectivcrm.domain.ui.Page;
import com.effectivcrm.domain.ui.PageList;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;

@Slf4j
public class StartupDataLoadingListener implements
		ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {

		System.out
				.println("######## Handling context refresh event  ############# ");

		HazelcastInstance client = event.getApplicationContext().getBean(
				"hazelCastClient", HazelcastInstance.class);

		try {
			Resource resources[] = event.getApplicationContext().getResources(
					"classpath:/toolbar/tb-*.json");

			for (Resource r : resources) {

				System.out.println("######## Found resource - "
						+ r.getFilename());

				loadMenu(r, client);
			}

			IMap<String, Form> formMap = client.getMap("forms");
			FormManager formManger = event.getApplicationContext().getBean(FormManager.class);
			
			formManger.load(formMap);
			

		} catch (Exception e) {
			throw new RuntimeException("Error loading configuration at startup.", e);
		}

	}

	

	private void loadMenu(Resource resource, HazelcastInstance client)
			throws Exception {
		System.out.println("######## client - " + client);
		IMap<String, Page> pageMap = client.getMap("pages");

		ObjectMapper mapper = new ObjectMapper();
		PageList data = mapper.readValue(resource.getInputStream(),
				PageList.class);

		List<Page> pages = data.getPages();

		for (Page p : pages) {
			System.out.println("######## Page Id - " + p.getId());
			pageMap.put(p.getId(), p);
		}

	}

}
